package com.silverbox.sweeporder.controller.pay;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import com.silverbox.sweeporder.controller.pay.entryvo.VipPayEntryDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.silverbox.core.result.CoreResponse;
import com.silverbox.core.result.CoreResponse.StatusInfo;
import com.silverbox.core.util.StringUtils;
import com.silverbox.sweeporder.controller.pay.entryvo.AlipayEntryVO;
import com.silverbox.sweeporder.controller.pay.entryvo.PayTradeEntryVO;
import com.silverbox.sweeporder.controller.pay.entryvo.WechatPayEntryVO;
import com.silverbox.sweeporder.controller.pay.vo.AlipayVO;
import com.silverbox.sweeporder.controller.pay.vo.WechatPayVO;
import com.silverbox.sweeporder.controller.waimai.outvo.WaimaiTradeInfo;
import com.silverbox.sweeporder.service.alipay.SweepAlipayService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 支付需要的接口，功能未定
 *
 * @author YTGHTGHS
 * @date 2017年12月7日
 * @description
 */
@Controller
@RequestMapping("pay")
@Api(tags = { "支付接口" })
public class PayController {

    private static Logger logger = LoggerFactory.getLogger(PayController.class);

    @Autowired
    private SweepAlipayService sweepAlipayService;

    @RequestMapping(value = "aliPayV2", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "扫码下单支付宝支付(可调用)")
    public CoreResponse<AlipayVO> aliPay(HttpServletResponse response, @RequestBody(required = true) AlipayEntryVO alipayEntry) {

        CoreResponse<AlipayVO> res = new CoreResponse<AlipayVO> ();
       // logger.info("扫码下单支付宝支付参数alipayEntry="+JSONObject.toJSONString(alipayEntry));
        if (alipayEntry == null || alipayEntry.getStoreId() == null || StringUtils.isEmpty(alipayEntry.getBuyerId())
                || StringUtils.isEmpty(alipayEntry.getOrderNum())) {
            res.setStatusInfo(StatusInfo.ERROR_40002);
            res.setSubMsg("参数异常!请检查参数");
            return res;
        }
        res = sweepAlipayService.alipay(response,alipayEntry);
        return res;
    }

    /**
     * 支付宝支付成功异步回调
     *
     */
    @RequestMapping(value = "payNofify", method = RequestMethod.POST)
    @ResponseBody
//	@ApiOperation(value = "支付回调")
    public String payNofify(@RequestParam Map<String, Object> param) {
        try {
            long startTime = System.currentTimeMillis();
            logger.info("进入支付宝支付异步回调=========="+param);
            sweepAlipayService.payNotify(param);
            long endTime = System.currentTimeMillis();
            logger.info("payNotity支付回调===========orderNum="+param.get("out_trade_no")+"=======接口调用时间="+(endTime-startTime));
            return "success";
        } catch (Exception e) {
            logger.error(e.getMessage());
            return "";
        }
    }

    @RequestMapping(value = "vipPayV2", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "扫码下单会员卡支付(可调用)")
    public CoreResponse<StatusInfo> vipPay(@RequestBody (required = true) VipPayEntryDto vipPayEntry) {
        CoreResponse<StatusInfo> res = new CoreResponse<StatusInfo>();
        if (vipPayEntry == null || StringUtils.isEmpty(vipPayEntry.getOrderNum())
                || StringUtils.isEmpty(vipPayEntry.getUid())) {
            res.setStatusInfo(StatusInfo.ERROR_40002);
            return res;
        }
        res = sweepAlipayService.vipPay(vipPayEntry);
        return res;
    }

    /**
     * 撤销支付宝等待支付的订单
     *
     * @param shopperId
     * @param orderNum
     * @param outTradeNo
     * @param cancelJSON
     */
    @RequestMapping(value = "/cancel", method = RequestMethod.POST)
    @ResponseBody
//	@ApiOperation(value = "撤销支付宝等待支付的订单（开发中）")
    public CoreResponse<StatusInfo> cancel(@RequestParam(required = true) Integer shopperId, @RequestParam(required = true) String orderNum,
                                           @RequestParam(required = false) String outTradeNo, @RequestParam(required = false) String cancelJSON) {
        CoreResponse<StatusInfo> res = new CoreResponse<StatusInfo>();
        sweepAlipayService.cancelAlipayOrder(shopperId, orderNum, outTradeNo, cancelJSON);
        return res;
    }


    @RequestMapping(value = "wechatPay", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "扫码下单微信支付(可调用)")
    public CoreResponse<WechatPayVO> wechatPay(HttpServletResponse response, @RequestBody (required = true) WechatPayEntryVO wechatPayEntry) {
        CoreResponse<WechatPayVO> res = new CoreResponse<WechatPayVO>();
        if(wechatPayEntry != null){
            if(StringUtils.isEmpty(wechatPayEntry.getOrderNum())){
                res.setSubMsg("订单号不存在或者为空");
                res.setStatusInfo(StatusInfo.ERROR_40002);
            }else if(StringUtils.isEmpty(wechatPayEntry.getBuyerId())){
                res.setSubMsg("用户id不存在或者为空");
                res.setStatusInfo(StatusInfo.ERROR_40002);
            }else if(StringUtils.isEmpty(wechatPayEntry.getBuyerNick())){
                res.setSubMsg("用户昵称不存在或者为空");
                res.setStatusInfo(StatusInfo.ERROR_40002);
            }else{
                res = sweepAlipayService.wechatPay(response,wechatPayEntry);
            }
        }else{
            res.setSubMsg("未传入任何参数");
            res.setStatusInfo(StatusInfo.ERROR_40002);
        }
        return res;
    }

    @RequestMapping(value = "alipayRefund", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "在线订单退款接口")
    public CoreResponse<Map<String, Object>> alipayRefund(@RequestParam(required = true) String orderNum,
                                                          String refundReason) {
        CoreResponse<Map<String, Object>> res = new CoreResponse<Map<String, Object>>();
        if (StringUtils.isEmpty(orderNum)) {
            res.setStatusInfo(StatusInfo.ERROR_40001);
            return res;
        }
        boolean flag = sweepAlipayService.updateAlipayRefund(orderNum, refundReason);
        Map<String, Object> map = new HashMap<String, Object>();
        if (flag) {
            map.put("success", true);
            map.put("msg", "申请退款成功");
        } else {
            map.put("success", false);
            map.put("msg", "申请退款失败");
        }
        res.setData(map);
        return res;
    }

    @RequestMapping(value = "payTradeInfo",  method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询第三方支付结果")
    public CoreResponse<WaimaiTradeInfo> getPayTradeInfo(@RequestBody(required = true) PayTradeEntryVO payTradeEntryVO) {
        CoreResponse<WaimaiTradeInfo> res = new CoreResponse<WaimaiTradeInfo>();
        if (payTradeEntryVO == null || StringUtils.isEmpty(payTradeEntryVO.getOrderNum())
                || payTradeEntryVO.getCount() == null) {
            res.setStatusInfo(StatusInfo.ERROR_40002);
            res.setSubMsg("参数有误");
            return res;
        }
        WaimaiTradeInfo tradeInfo = sweepAlipayService.getPayTradeInfo(payTradeEntryVO);
        res.setData(tradeInfo);
        return res;
    }
}
